<?php
$box_title= "Add Emails";
$box_contents = "";

$emails = @$_POST['emails'];
$subject = @trim($_POST['subject']);
$message = @trim($_POST['message']);
$sendNow = ($_POST['sendNow']) ? $_POST['sendNow'] : 0;

if(!empty($emails) && !empty($subject) && !empty($message)) {
    $headers  = 'MIME-Version: 1.0' . "\r\n";
    $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
    $headers .= 'From: <'. $site['email']. '> ' . "\r\n";
    $headers .= 'X-Mailer: PHP/' . phpversion();

    sql_query("INSERT INTO messages(subject, message) values('".$subject."', '".$message."');");
    $message_id = mysql_insert_id();

    $emails = preg_split('/[,]/', $emails);
    $emails = preg_split('/[\n]/', $emails);
    foreach($emails as $key => $email) {
        preg_match('/<(.*)>/si', $email, $matches);

        if(!empty($matches[1])) {
            $email = trim($matches[1]);
        } else {
            $email = trim($email);
        }
        if(!empty($email)) {
            sql_query("INSERT INTO emails(email, message_id, sent) values('".$email."', '$message_id', '$sendNow');");
            $email_id = mysql_insert_id();
            if($sendNow) {
                if(mail($email, $subject, $message, $headers)) {
                    echo 'sent to: '.$email.'<br>';
                    sql_query("UPDATE emails SET sent='1' WHERE id='".$email_id."'");
                } else {
                    echo 'not sent to: '.$email.'<br>';
                }
            }
        }
    }
    echo "<script> window.location='index.php?m=emails'; </script>";
} else {
    $box_contents .= "<div class=\"highlight\">Error: Message must not be empty</div>";
}
?>
